# -*- coding: utf-8 -*-

'''
This file is a textobot App Text Capture plugin.
'''

import os
import codecs
import urllib2
import time
import subprocess
import json

# it's only for VSCode Textobot-Run command
# turn to 0 before you pack this plugin
# turn to 1 if you want to run directly from VSCode
dev_mode = 0

# turn to 1 when you finished the plugin development
# and run at least one time to flush remote server side global code 
# otherwise will conflict with the release TB plugin
dev_clear_hotcode = 1

# captured texts
texts = None

if not dev_mode:
    # this plugin package's root directory
    pkg_root = os.path.dirname(__file__)

    # pickup this plugin's version dynamically
    with open(pkg_root + '/textobot.json', 'r') as fp:
        pkginfo = json.load(fp)
        pkg_version = pkginfo['version']

def start_task():
    global texts
    texts = {}
    print('Running TextCapture plugin, reset texts to %s.' % (str(texts)))

def stop_task():
    global texts
    print('Stopped TextCapture plugin.')
    if texts is None:
        print('texts is None.')
        return
    print('#### TextCapture Begin ####')
    for k in texts.keys():
        print(k)
        for v in texts[k]:
            print('\t%s' % (v))
    print('#### TextCapture End ####')
    texts = None

# handler for text views
def proc_event_views(pts, txts):
    global texts
    for i in range(0, len(pts)):
        if txts[i] not in texts.keys():
            texts[txts[i]] = set()
        curset = texts[txts[i]]
        if pts[i] not in curset:
            curset.add(pts[i])
    if dev_mode:
        print(texts)

# handler for dialog
def proc_event_dialog(pts, txts):
    proc_event_views(pts, txts)

# handler for event
def TB_on_event(dictarg):
    if texts is None:
        return
    event = dictarg['event']
    if event == 'texts':
        proc_event_views(dictarg.keys(), dictarg.values())
    elif event == 'dlgtexts':
        proc_event_dialog(dictarg.keys(), dictarg.values())
    return {}

# handler for main
def TB_main(dictarg):
    event = dictarg['event']
    if event == 'install':
        print('Installed TextCapture plugin.')
    elif event == 'uninstall':
        print('Uninstalled TextCapture plugin.')
    elif event == 'start':
        start_task()
    elif event == 'stop':
        stop_task()
    return {}

# it's only for VSCode Textobot-Run command, can only recv TB_on_event
if dev_mode:
    TB_clear_log()
    # only available in dev mode
    if dev_clear_hotcode:
        TB_event_callback = None
        print('Cleared dev hot code...')
    else:
        TB_event_callback = TB_on_event
        start_task()
else:
    print('The TextCapture plugin(%s) is waiting for event ...' % (pkg_version))
